import React, { useEffect } from 'react';
// @ts-ignore
import * as THREE from 'three';
// @ts-ignore
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const Demo2: React.FC = () => {
  const init = () => {
    const container = document.getElementById('webgl');
    if (container) {
      container.innerHTML = '';
    }
    // 创建3D场景对象Scene
    const scene = new THREE.Scene();

    const vertices = [];
    for (let i = 0; i < 1000; i++) {
      const x = THREE.MathUtils.randFloatSpread(1000);
      const y = THREE.MathUtils.randFloatSpread(1000);
      const z = THREE.MathUtils.randFloatSpread(1000);
      vertices.push({
        x,
        y,
        z,
      });
    }

    for (let vertex of vertices) {
      const geometry = new THREE.SphereGeometry(1);
      const material = new THREE.MeshBasicMaterial({ color: '#000' });
      const sphere = new THREE.Mesh(geometry, material);
      sphere.position.set(vertex.x, vertex.y, vertex.z);
      scene.add(sphere);
    }

    // AxesHelper：辅助观察的坐标系
    const axesHelper = new THREE.AxesHelper(150);
    scene.add(axesHelper);

    const width = 800; //宽度
    const height = 500; //高度

    // 实例化一个透视投影相机对象
    const camera = new THREE.PerspectiveCamera(20, width / height, 0.1, 3000);
    camera.position.set(300, 300, 300);
    camera.lookAt(0, 0, 0);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
    renderer.setClearColor('#ffffff', 1); //设置背景颜色

    renderer.render(scene, camera); //执行渲染操作
    container?.appendChild(renderer.domElement);
    // 设置相机控件轨道控制器OrbitControls
    const controls = new OrbitControls(camera, renderer.domElement);
    // 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
    controls.addEventListener('change', function () {
      renderer.render(scene, camera); //执行渲染操作
    }); //监听鼠标、键盘事件
  };
  useEffect(() => {
    init();
  }, []);
  return <div id="webgl"></div>;
};

export default Demo2;
